/**
 * 证券交易日历选择器组件
 * 用于选择交易日，支持交易日历数据加载和显示
 */
(function(window, $) {
    'use strict';

    /**
     * SecurityDatePicker 构造函数
     * @param {Object} options 配置选项
     * @param {string} options.inputId 输入框ID
     * @param {string} options.calendarId 日历容器ID
     * @param {string} options.apiPrefix API前缀
     * @param {Function} options.onDateSelect 日期选择回调函数
     */
    function SecurityDatePicker(options) {
        this.options = $.extend({}, {
            inputId: 'dateSelect',
            calendarId: 'dateCalendar',
            apiPrefix: '',
            onDateSelect: null,
            maxDate: null,  // 最大可选日期，null表示不限制
            autoInitDate: true  // 是否自动设置默认日期，false表示不自动设置
        }, options);

        this.currentDate = null;
        this.tradingCalendarData = {};
        this.calendarYear = null;
        this.calendarMonth = null;

        // 注入样式
        this.injectStyles();
    }

    /**
     * 注入CSS样式
     */
    SecurityDatePicker.prototype.injectStyles = function() {
        if ($('#security-date-picker-styles').length > 0) {
            return; // 样式已存在，不重复注入
        }

        var styles = `
        <style id="security-date-picker-styles">
        /* 日期选择器日历样式 */
        .date-calendar {
            font-family: Arial, sans-serif;
        }
        
        .calendar-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
            padding: 5px 0;
            position: relative;
        }
        
        .calendar-nav {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .calendar-nav button {
            padding: 3px 8px;
            border: 1px solid #ddd;
            background: white;
            cursor: pointer;
            border-radius: 3px;
            font-size: 12px;
        }
        
        .calendar-nav button:hover {
            background: #f5f5f5;
        }
        
        .calendar-title {
            font-size: 16px;
            font-weight: bold;
            color: #333;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            flex: 1;
            text-align: center;
            user-select: none;
        }
        
        .calendar-title-icon {
            cursor: pointer;
            color: #666;
            font-size: 14px;
            padding: 4px;
            border-radius: 4px;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            width: 24px;
            height: 24px;
            position: relative;
        }
        
        .calendar-title-icon:hover {
            background-color: #f0f0f0;
            color: #007bff;
            transform: rotate(90deg);
        }
        
        .calendar-year-month-selector {
            display: none;
            position: absolute;
            top: calc(100% + 5px);
            left: 20px;
            right: 20px;
            background: white;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            z-index: 1001;
            padding: 8px;
            width: calc(100% - 40px);
            max-width: calc(100% - 40px);
            box-sizing: border-box;
            overflow: hidden;
        }
        
        .calendar-year-month-selector.show {
            display: block;
        }
        
        .year-month-selector-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
            padding-bottom: 6px;
            border-bottom: 1px solid #e0e0e0;
        }
        
        .year-month-selector-title {
            font-size: 12px;
            font-weight: 600;
            color: #333;
        }
        
        .year-month-selector-close {
            cursor: pointer;
            font-size: 14px;
            color: #999;
            padding: 2px 4px;
            border-radius: 3px;
            transition: all 0.2s ease;
            line-height: 1;
        }
        
        .year-month-selector-close:hover {
            color: #333;
            background-color: #f5f5f5;
        }
        
        .year-month-selector-content {
            display: flex;
            flex-direction: column;
            gap: 8px;
            margin-bottom: 8px;
            padding: 4px 0;
        }
        
        .year-selector,
        .month-selector {
            flex: 0 0 auto;
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 6px;
            padding: 2px 0;
            box-sizing: border-box;
        }
        
        .year-selector label,
        .month-selector label {
            display: inline-block;
            font-size: 12px;
            color: #666;
            font-weight: 500;
            white-space: nowrap;
            min-width: 28px;
            flex-shrink: 0;
            text-align: left;
        }
        
        .year-selector select,
        .month-selector select {
            flex: 1 1 auto;
            min-width: 0;
            max-width: 80px;
            padding: 4px 6px;
            border: 1px solid #e0e0e0;
            border-radius: 4px;
            font-size: 12px;
            cursor: pointer;
            outline: none;
            background: white;
            transition: all 0.2s ease;
            box-sizing: border-box;
        }
        
        .year-selector select:hover,
        .month-selector select:hover {
            border-color: #007bff;
        }
        
        .year-selector select:focus,
        .month-selector select:focus {
            border-color: #007bff;
            box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.1);
        }
        
        .year-month-selector-actions {
            display: flex;
            justify-content: flex-end;
            gap: 6px;
            margin-top: 6px;
            padding-top: 6px;
            border-top: 1px solid #e0e0e0;
        }
        
        .year-month-selector-btn {
            padding: 3px 8px;
            border: 1px solid #ddd;
            background: white;
            border-radius: 4px;
            cursor: pointer;
            font-size: 11px;
            font-weight: 500;
            transition: all 0.2s ease;
        }
        
        .year-month-selector-btn:hover {
            background: #f8f9fa;
            border-color: #ccc;
        }
        
        .year-month-selector-btn.primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            box-shadow: 0 1px 3px rgba(102, 126, 234, 0.3);
        }
        
        .year-month-selector-btn.primary:hover {
            background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
            box-shadow: 0 2px 4px rgba(102, 126, 234, 0.4);
        }
        
        .calendar-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 12px;
        }
        
        .calendar-table th,
        .calendar-table td {
            border: 1px solid #eee;
            padding: 4px 2px;
            text-align: center;
            width: 14.28%;
            height: 24px;
        }
        
        .calendar-table th {
            background-color: #f8f9fa;
            font-weight: bold;
            font-size: 11px;
        }
        
        .calendar-table .trading-day {
            background-color: #d4edda;
            color: #155724;
            cursor: pointer;
        }
        
        .calendar-table .trading-day:hover {
            background-color: #c3e6cb;
        }
        
        .calendar-table .non-trading-day {
            background-color: #f8d7da;
            color: #721c24;
            cursor: not-allowed;
            opacity: 0.6;
        }
        
        .calendar-table .non-trading-day:hover {
            background-color: #f5c6cb;
        }
        
        .calendar-table .weekend {
            background-color: #e9ecef;
            color: #495057;
        }
        
        .calendar-table .holiday {
            background-color: #fff3cd;
            color: #856404;
        }
        
        .calendar-table .other-month {
            color: #ddd;
        }
        
        .calendar-table .today {
            position: relative;
            background-color: #007bff !important;
            color: white !important;
            font-weight: bold;
        }
        
        .calendar-table .today::after {
            content: "今";
            position: absolute;
            top: 1px;
            right: 1px;
            font-size: 8px;
            font-weight: bold;
            color: white;
        }
        
        .calendar-table .selected {
            background-color: #28a745 !important;
            color: white !important;
            font-weight: bold;
        }
        
        /* 休市的标记样式 */
        .calendar-table .holiday-mark {
            position: relative;
        }
        
        .calendar-table .holiday-mark::after {
            content: "休";
            position: absolute;
            top: 2px;
            right: 2px;
            font-size: 10px;
            font-weight: bold;
            color: #dc3545;
        }
        </style>
        `;

        $('head').append(styles);
    };

    /**
     * 初始化组件
     */
    SecurityDatePicker.prototype.init = function() {
        var self = this;

        // 初始化输入框
        this.initInput();

        // 绑定事件
        this.bindEvents();

        // 初始化交易日历数据
        this.initTradingCalendarData();

        // 设置默认日期（如果启用自动设置）
        if (this.options.autoInitDate) {
            this.initDateSelect();
        }

        // 将实例保存到全局，供日历HTML中的onclick使用
        window['securityDatePickerInstance_' + this.options.calendarId] = this;
    };

    /**
     * 初始化输入框
     */
    SecurityDatePicker.prototype.initInput = function() {
        var $input = $('#' + this.options.inputId);
        if ($input.length === 0) {
            console.error('输入框不存在:', this.options.inputId);
            return;
        }
        $input.attr('readonly', true).css('cursor', 'pointer');
    };

    /**
     * 绑定事件
     */
    SecurityDatePicker.prototype.bindEvents = function() {
        var self = this;
        var eventNamespace = '.securityDatePicker_' + this.options.calendarId;

        // 解绑之前的事件，避免重复绑定
        $('#' + this.options.inputId).off('click' + eventNamespace);
        $(document).off('click' + eventNamespace);

        // 绑定输入框点击事件
        var $input = $('#' + this.options.inputId);
        if ($input.length > 0) {
            $input.on('click' + eventNamespace, function(e) {
                e.stopPropagation();
                console.log('日期选择框被点击');
                self.showDateCalendar();
            });
        } else {
            console.error('日期选择输入框不存在:', this.options.inputId);
        }

        // 点击其他地方隐藏日历
        $(document).on('click' + eventNamespace, function(e) {
            // 检查是否点击的是日期选择相关的元素
            var $target = $(e.target);
            var isDatePickerElement = $target.closest('#' + self.options.inputId).length > 0 ||
                                     $target.closest('#' + self.options.calendarId).length > 0 ||
                                     $target.closest('.calendar-title-icon').length > 0 ||
                                     $target.closest('.calendar-prev-month').length > 0 ||
                                     $target.closest('.calendar-next-month').length > 0 ||
                                     $target.closest('.year-month-selector').length > 0 ||
                                     $target.closest('.calendar-table').length > 0;
            
            if (!isDatePickerElement) {
                self.hideDateCalendar();
            }
        });
    };

    /**
     * 显示日期日历
     */
    SecurityDatePicker.prototype.showDateCalendar = function() {
        var $calendar = $('#' + this.options.calendarId);
        if ($calendar.length === 0) {
            console.error('日历容器不存在:', this.options.calendarId);
            return;
        }

        if ($calendar.is(':visible')) {
            this.hideDateCalendar();
            return;
        }

        // 初始化当前显示的年份和月份
        if (this.currentDate) {
            var date = new Date(this.currentDate);
            this.calendarYear = date.getFullYear();
            this.calendarMonth = date.getMonth();
        } else {
            var today = new Date();
            this.calendarYear = today.getFullYear();
            this.calendarMonth = today.getMonth();
        }

        // 生成日历HTML
        var calendarHtml = this.generateDateCalendarWithYearMonth(this.calendarYear, this.calendarMonth);
        $calendar.html(calendarHtml);
        $calendar.show();

        // 绑定年月选择器事件
        this.bindYearMonthSelectorEvents();
    };

    /**
     * 隐藏日期日历
     */
    SecurityDatePicker.prototype.hideDateCalendar = function() {
        $('#' + this.options.calendarId).hide();
    };

    /**
     * 使用指定年份和月份生成日历
     */
    SecurityDatePicker.prototype.generateDateCalendarWithYearMonth = function(year, month) {
        var self = this;
        var monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', 
                         '七月', '八月', '九月', '十月', '十一月', '十二月'];
        
        var html = '<div class="date-calendar">';
        html += '<div class="calendar-header">';
        html += '<div class="calendar-nav">';
        html += '<button class="calendar-prev-month" data-direction="-1">&lt;</button>';
        html += '</div>';
        html += '<div class="calendar-title">';
        html += '<span class="calendar-title-text">' + year + '年' + monthNames[month] + '</span>';
        html += '<i class="fa fa-cog calendar-title-icon" title="选择年月"></i>';
        html += '</div>';
        html += '<div class="calendar-nav">';
        html += '<button class="calendar-next-month" data-direction="1">&gt;</button>';
        html += '</div>';
        html += '<div class="calendar-year-month-selector" id="yearMonthSelector">';
        html += '<div class="year-month-selector-header">';
        html += '<span class="year-month-selector-title">选择年月</span>';
        html += '<span class="year-month-selector-close">&times;</span>';
        html += '</div>';
        html += '<div class="year-month-selector-content">';
        html += '<div class="year-selector">';
        html += '<label>年份</label>';
        html += '<select id="yearSelector">';
        var currentYear = new Date().getFullYear();
        for (var y = currentYear - 10; y <= currentYear + 10; y++) {
            var selected = y === year ? ' selected' : '';
            html += '<option value="' + y + '"' + selected + '>' + y + '年</option>';
        }
        html += '</select>';
        html += '</div>';
        html += '<div class="month-selector">';
        html += '<label>月份</label>';
        html += '<select id="monthSelector">';
        for (var m = 0; m < 12; m++) {
            var selected = m === month ? ' selected' : '';
            html += '<option value="' + m + '"' + selected + '>' + monthNames[m] + '</option>';
        }
        html += '</select>';
        html += '</div>';
        html += '</div>';
        html += '<div class="year-month-selector-actions">';
        html += '<button class="year-month-selector-btn">取消</button>';
        html += '<button class="year-month-selector-btn primary">确定</button>';
        html += '</div>';
        html += '</div>';
        html += '</div>';
        
        html += '<table class="calendar-table">';
        html += '<thead><tr>';
        html += '<th>日</th><th>一</th><th>二</th><th>三</th><th>四</th><th>五</th><th>六</th>';
        html += '</tr></thead>';
        
        html += '<tbody>';
        
        var firstDay = new Date(year, month, 1);
        var lastDay = new Date(year, month + 1, 0);
        var firstWeekday = firstDay.getDay();
        var daysInMonth = lastDay.getDate();
        
        var today = new Date();
        var isCurrentMonth = year == today.getFullYear() && month == today.getMonth();
        
        // 生成日历行
        var day = 1;
        for (var week = 0; week < 6 && day <= daysInMonth; week++) {
            html += '<tr>';
            
            for (var weekday = 0; weekday < 7; weekday++) {
                if (week == 0 && weekday < firstWeekday) {
                    // 上个月的日期
                    var prevMonth = month == 0 ? 11 : month - 1;
                    var prevYear = month == 0 ? year - 1 : year;
                    var prevLastDay = new Date(prevYear, prevMonth + 1, 0).getDate();
                    var prevDay = prevLastDay - firstWeekday + weekday + 1;
                    html += '<td class="other-month">' + prevDay + '</td>';
                } else if (day <= daysInMonth) {
                    // 当前月的日期
                    var dateStr = year + '-' + this.padZero(month + 1) + '-' + this.padZero(day);
                    var isToday = isCurrentMonth && day == today.getDate();
                    var isSelected = dateStr === this.currentDate;
                    
                    // 获取交易日历数据
                    var calendarItem = this.tradingCalendarData[dateStr];
                    var isTradingDay = calendarItem && calendarItem.tradingDayFlag === 1;
                    var isWeekend = weekday == 0 || weekday == 6;
                    
                    // 根据交易日状态设置样式和点击事件
                    var cellClass = '';
                    var clickEvent = '';
                    
                    // 检查是否超过最大可选日期
                    var isExceedMaxDate = false;
                    if (this.options.maxDate) {
                        var maxDateStr;
                        if (this.options.maxDate instanceof Date) {
                            maxDateStr = this.options.maxDate.toISOString().split('T')[0];
                        } else {
                            maxDateStr = this.options.maxDate;
                        }
                        if (dateStr > maxDateStr) {
                            isExceedMaxDate = true;
                        }
                    }
                    
                    // 只有当交易日历数据存在时，才根据tradingDayFlag设置样式
                    if (calendarItem) {
                        if (calendarItem.tradingDayFlag === 1 && !isExceedMaxDate) {
                            cellClass = 'trading-day';
                            clickEvent = 'onclick="window.securityDatePickerInstance_' + this.options.calendarId + '.selectDate(\'' + dateStr + '\'); event.stopPropagation(); return false;"';
                        } else {
                            cellClass = 'non-trading-day';
                            clickEvent = ''; // 非交易日或超过最大日期不可点击
                            // 只有非周末的非交易日才添加休市标记
                            if (!isWeekend && !isExceedMaxDate) {
                                cellClass += ' holiday-mark';
                            }
                        }
                    } else {
                        // 没有交易日历数据时，默认可以点击（假设是交易日），但需要检查最大日期
                        if (!isExceedMaxDate) {
                            clickEvent = 'onclick="window.securityDatePickerInstance_' + this.options.calendarId + '.selectDate(\'' + dateStr + '\'); event.stopPropagation(); return false;"';
                        } else {
                            cellClass = 'non-trading-day';
                        }
                    }
                    
                    if (isToday) cellClass += ' today';
                    if (isSelected) cellClass += ' selected';
                    if (isWeekend && !calendarItem) {
                        // 没有交易日历数据时，周末显示为weekend样式
                        cellClass = 'weekend';
                    } else if (isWeekend && calendarItem && !isTradingDay) {
                        // 有交易日历数据且是非交易日时，周末显示为weekend样式
                        cellClass = 'weekend';
                    }
                    
                    html += '<td class="' + cellClass + '" ' + clickEvent + '>' + day + '</td>';
                    day++;
                } else {
                    // 下个月的日期
                    var nextDay = day - daysInMonth;
                    html += '<td class="other-month">' + nextDay + '</td>';
                    day++;
                }
            }
            
            html += '</tr>';
        }
        
        html += '</tbody></table></div>';
        return html;
    };

    /**
     * 切换月份
     */
    SecurityDatePicker.prototype.changeMonth = function(direction) {
        // 更新月份
        this.calendarMonth += direction;
        
        // 处理年份边界
        if (this.calendarMonth < 0) {
            this.calendarMonth = 11;
            this.calendarYear--;
        } else if (this.calendarMonth > 11) {
            this.calendarMonth = 0;
            this.calendarYear++;
        }
        
        // 重新生成日历
        var calendarHtml = this.generateDateCalendarWithYearMonth(this.calendarYear, this.calendarMonth);
        $('#' + this.options.calendarId).html(calendarHtml);
        
        // 重新绑定年月选择器事件
        this.bindYearMonthSelectorEvents();
    };

    /**
     * 选择日期
     */
    SecurityDatePicker.prototype.selectDate = function(dateStr) {
        console.log('选择日期:', dateStr);
        // 查找最近一个交易日
        var nearestTradingDay = this.findNearestTradingDay(dateStr);
        console.log('最近交易日:', nearestTradingDay);
        $('#' + this.options.inputId).val(nearestTradingDay);
        this.currentDate = nearestTradingDay;
        this.hideDateCalendar();
        
        // 触发回调
        if (this.options.onDateSelect) {
            console.log('触发日期选择回调');
            this.options.onDateSelect(nearestTradingDay);
        } else {
            console.warn('日期选择回调未定义');
        }
    };

    /**
     * 查找最近一个交易日
     */
    SecurityDatePicker.prototype.findNearestTradingDay = function(selectedDate) {
        // 如果交易日历数据还没有加载完成，使用简单的逻辑判断
        if (Object.keys(this.tradingCalendarData).length === 0) {
            return this.findNearestTradingDaySimple(selectedDate);
        }
        
        // 首先检查指定日期是否为交易日
        var calendarItem = this.tradingCalendarData[selectedDate];
        if (calendarItem && calendarItem.tradingDayFlag === 1) {
            return selectedDate;
        }
        
        // 遍历交易日历，按日期倒序，过滤出交易日
        var tradingDaysList = [];
        for (var dateStr in this.tradingCalendarData) {
            var item = this.tradingCalendarData[dateStr];
            if (item && item.tradingDayFlag === 1 && dateStr <= selectedDate) {
                tradingDaysList.push(dateStr);
            }
        }
        
        // 按日期倒序排列，返回最近的一个交易日
        tradingDaysList.sort().reverse();
        if (tradingDaysList.length > 0) {
            return tradingDaysList[0];
        }
        
        // 如果找不到，使用简单逻辑
        return this.findNearestTradingDaySimple(selectedDate);
    };
    
    /**
     * 查找前一个交易日
     */
    SecurityDatePicker.prototype.findPreviousTradingDay = function(selectedDate) {
        // 如果交易日历数据还没有加载完成，使用简单的逻辑判断
        if (Object.keys(this.tradingCalendarData).length === 0) {
            var date = new Date(selectedDate);
            date.setDate(date.getDate() - 1);
            var prevDateStr = date.toISOString().split('T')[0];
            return this.findNearestTradingDaySimple(prevDateStr);
        }
        
        // 遍历交易日历，按日期倒序，过滤出交易日，找到小于指定日期的最近一个交易日
        var tradingDaysList = [];
        for (var dateStr in this.tradingCalendarData) {
            var item = this.tradingCalendarData[dateStr];
            if (item && item.tradingDayFlag === 1 && dateStr < selectedDate) {
                tradingDaysList.push(dateStr);
            }
        }
        
        // 按日期倒序排列，返回最近的一个交易日
        tradingDaysList.sort().reverse();
        if (tradingDaysList.length > 0) {
            return tradingDaysList[0];
        }
        
        // 如果找不到，使用简单逻辑
        var date = new Date(selectedDate);
        date.setDate(date.getDate() - 1);
        var prevDateStr = date.toISOString().split('T')[0];
        return this.findNearestTradingDaySimple(prevDateStr);
    };

    /**
     * 查找下一个交易日
     */
    SecurityDatePicker.prototype.findNextTradingDay = function(selectedDate) {
        // 如果交易日历数据还没有加载完成，使用简单的逻辑判断
        if (Object.keys(this.tradingCalendarData).length === 0) {
            var date = new Date(selectedDate);
            date.setDate(date.getDate() + 1);
            var nextDateStr = date.toISOString().split('T')[0];
            return this.findNextTradingDaySimple(nextDateStr);
        }
        
        // 遍历交易日历，按日期正序，过滤出交易日，找到大于指定日期的最近一个交易日
        var tradingDaysList = [];
        for (var dateStr in this.tradingCalendarData) {
            var item = this.tradingCalendarData[dateStr];
            if (item && item.tradingDayFlag === 1 && dateStr > selectedDate) {
                tradingDaysList.push(dateStr);
            }
        }
        
        // 按日期正序排列，返回最近的一个交易日
        tradingDaysList.sort();
        if (tradingDaysList.length > 0) {
            return tradingDaysList[0];
        }
        
        // 如果找不到，使用简单逻辑
        var date = new Date(selectedDate);
        date.setDate(date.getDate() + 1);
        var nextDateStr = date.toISOString().split('T')[0];
        return this.findNextTradingDaySimple(nextDateStr);
    };

    /**
     * 简单的下一个交易日查找逻辑（当交易日历数据未加载时使用）
     */
    SecurityDatePicker.prototype.findNextTradingDaySimple = function(selectedDate) {
        var date = new Date(selectedDate);
        var dayOfWeek = date.getDay(); // 0=周日, 1=周一, ..., 6=周六
        
        // 如果是工作日（周一到周五），直接返回
        if (dayOfWeek >= 1 && dayOfWeek <= 5) {
            return selectedDate;
        }
        
        // 如果是周末，向后查找最近的工作日
        if (dayOfWeek === 0) { // 周日
            date.setDate(date.getDate() + 1); // 到周一
        } else if (dayOfWeek === 6) { // 周六
            date.setDate(date.getDate() + 2); // 到周一
        }
        
        var year = date.getFullYear();
        var month = String(date.getMonth() + 1).padStart(2, '0');
        var day = String(date.getDate()).padStart(2, '0');
        return year + '-' + month + '-' + day;
    };

    /**
     * 简单的交易日查找逻辑（当交易日历数据未加载时使用）
     */
    SecurityDatePicker.prototype.findNearestTradingDaySimple = function(selectedDate) {
        var date = new Date(selectedDate);
        var dayOfWeek = date.getDay(); // 0=周日, 1=周一, ..., 6=周六
        
        // 如果是工作日（周一到周五），直接返回
        if (dayOfWeek >= 1 && dayOfWeek <= 5) {
            return selectedDate;
        }
        
        // 如果是周末，向前查找最近的工作日
        if (dayOfWeek === 0) { // 周日
            date.setDate(date.getDate() - 2); // 回到周五
        } else if (dayOfWeek === 6) { // 周六
            date.setDate(date.getDate() - 1); // 回到周五
        }
        
        var year = date.getFullYear();
        var month = String(date.getMonth() + 1).padStart(2, '0');
        var day = String(date.getDate()).padStart(2, '0');
        return year + '-' + month + '-' + day;
    };

    /**
     * 数字补零
     */
    SecurityDatePicker.prototype.padZero = function(num) {
        return num < 10 ? '0' + num : num;
    };

    /**
     * 绑定年月选择器事件
     */
    SecurityDatePicker.prototype.bindYearMonthSelectorEvents = function() {
        var self = this;
        var eventNamespace = '.securityDatePicker_' + this.options.calendarId;
        
        // 解绑之前的事件，避免重复绑定
        $(document).off('click' + eventNamespace, '.calendar-title-icon');
        $(document).off('click' + eventNamespace, '.year-month-selector-close, .year-month-selector-btn');
        $(document).off('click' + eventNamespace, '.calendar-prev-month, .calendar-next-month');
        
        // 点击齿轮图标显示/隐藏选择器
        $(document).on('click' + eventNamespace, '.calendar-title-icon', function(e) {
            e.stopPropagation();
            self.toggleYearMonthSelector(e);
        });
        
        // 点击关闭按钮或取消按钮关闭选择器
        $(document).on('click' + eventNamespace, '.year-month-selector-close, .year-month-selector-btn:not(.primary)', function(e) {
            e.stopPropagation();
            self.closeYearMonthSelector(e);
        });
        
        // 点击确定按钮确认选择
        $(document).on('click' + eventNamespace, '.year-month-selector-btn.primary', function(e) {
            e.stopPropagation();
            e.preventDefault();
            
            var yearSelector = $("#yearSelector");
            var monthSelector = $("#monthSelector");
            
            if (yearSelector.length === 0 || monthSelector.length === 0) {
                console.error("年月选择器不存在");
                self.closeYearMonthSelector(e);
                return;
            }
            
            var yearStr = yearSelector.val();
            var monthStr = monthSelector.val();
            
            if (!yearStr || yearStr === '' || !monthStr || monthStr === '') {
                console.error("年月选择器值无效，年份:", yearStr, "月份:", monthStr);
                self.closeYearMonthSelector(e);
                return;
            }
            
            var selectedYear = parseInt(yearStr);
            var selectedMonth = parseInt(monthStr);
            
            if (isNaN(selectedYear) || isNaN(selectedMonth) || selectedYear < 1900 || selectedYear > 2100 || selectedMonth < 0 || selectedMonth > 11) {
                console.error("年月参数无效，年份:", selectedYear, "月份:", selectedMonth);
                self.closeYearMonthSelector(e);
                return;
            }
            
            console.log("确认选择年月，年份:", selectedYear, "月份:", selectedMonth);
            
            // 先关闭选择器
            self.closeYearMonthSelector(e);
            
            // 延迟调用接口，确保选择器已关闭
            setTimeout(function() {
                // 加载指定年份的交易日历数据
                self.loadTradingCalendarDataForYear(selectedYear, selectedMonth);
            }, 100);
        });
        
        // 绑定月份切换按钮事件
        $(document).on('click' + eventNamespace, '.calendar-prev-month, .calendar-next-month', function(e) {
            e.preventDefault();
            e.stopPropagation();
            var direction = $(this).data('direction');
            self.changeMonth(direction);
        });
    };

    /**
     * 切换年月选择器显示/隐藏
     */
    SecurityDatePicker.prototype.toggleYearMonthSelector = function(event) {
        if (event) {
            event.stopPropagation();
        }
        var selector = $("#yearMonthSelector");
        if (selector.hasClass('show')) {
            selector.removeClass('show');
        } else {
            selector.addClass('show');
        }
    };

    /**
     * 关闭年月选择器
     */
    SecurityDatePicker.prototype.closeYearMonthSelector = function(event) {
        if (event) {
            event.stopPropagation();
        }
        $("#yearMonthSelector").removeClass('show');
    };

    /**
     * 初始化交易日历数据加载
     */
    SecurityDatePicker.prototype.initTradingCalendarData = function() {
        var self = this;
        var currentYear = new Date().getFullYear();
        console.log("开始初始化交易日历数据，年份:", currentYear);
        
        $.ajax({
            url: this.options.apiPrefix + "trading-calendar/list",
            type: "GET",
            data: { year: currentYear },
            dataType: 'json',
            success: function(data) {
                console.log("交易日历API响应:", data);
                if (data.code === 0 && data.data) {
                    // 将按月份分组的数据按日期组织
                    self.tradingCalendarData = {};
                    $.each(data.data, function(monthIndex, monthData) {
                        if (monthData && monthData.length > 0) {
                            $.each(monthData, function(index, item) {
                                if (item && item.date) {
                                    var dateStr = item.date.substring(0, 10); // 取日期部分
                                    self.tradingCalendarData[dateStr] = item;
                                }
                            });
                        }
                    });
                    console.log("成功加载交易日历数据，数量:", Object.keys(self.tradingCalendarData).length);
                    
                    // 交易日历数据加载完成后，重新设置默认日期（如果启用自动设置）
                    if (self.options.autoInitDate && Object.keys(self.tradingCalendarData).length > 0) {
                        // 获取当前时间
                        var now = new Date();
                        var currentHour = now.getHours();
                        var currentMinute = now.getMinutes();
                        var isAfter1500 = (currentHour > 15) || (currentHour === 15 && currentMinute >= 0);
                        
                        var todayStr = now.toISOString().split('T')[0];
                        var defaultDate;
                        
                        if (isAfter1500) {
                            // 当前时间大于15:00，默认选择当日
                            defaultDate = self.findNearestTradingDay(todayStr);
                        } else {
                            // 当前时间小于等于15:00，默认选择前一个交易日
                            defaultDate = self.findPreviousTradingDay(todayStr);
                        }
                        
                        self.setDate(defaultDate);
                        console.log("交易日历数据加载完成，当前时间:", currentHour + ":" + currentMinute, "重新设置默认日期:", defaultDate);
                    }
                } else {
                    console.log("未加载到交易日历数据，年份:", currentYear);
                }
            },
            error: function(xhr, status, error) {
                console.error("加载交易日历数据失败:", error);
            }
        });
    };

    /**
     * 加载指定年份的交易日历数据（用于切换年份时）
     */
    SecurityDatePicker.prototype.loadTradingCalendarDataForYear = function(year, month) {
        var self = this;
        
        // 参数验证
        if (!year || isNaN(year) || year < 1900 || year > 2100) {
            console.error("年份参数无效:", year);
            year = new Date().getFullYear();
        }
        
        if (month === undefined || month === null || isNaN(month) || month < 0 || month > 11) {
            console.error("月份参数无效:", month);
            month = new Date().getMonth();
        }
        
        // 更新当前显示的年份和月份
        this.calendarYear = year;
        this.calendarMonth = month;
        
        console.log("开始加载指定年份的交易日历数据，年份:", year, "月份:", month);
        
        // 先显示日历，不等待接口返回
        var calendarHtml = this.generateDateCalendarWithYearMonth(year, month);
        $('#' + this.options.calendarId).html(calendarHtml);
        this.bindYearMonthSelectorEvents();
        
        // 然后异步加载交易日历数据
        $.ajax({
            url: this.options.apiPrefix + "trading-calendar/list",
            type: "GET",
            data: { year: year },
            dataType: 'json',
            success: function(data) {
                console.log("交易日历API响应:", data);
                if (data && data.code === 0 && data.data) {
                    // 将按月份分组的数据按日期组织
                    $.each(data.data, function(monthIndex, monthData) {
                        if (monthData && monthData.length > 0) {
                            $.each(monthData, function(index, item) {
                                if (item && item.date) {
                                    var dateStr = item.date.substring(0, 10); // 取日期部分
                                    self.tradingCalendarData[dateStr] = item;
                                }
                            });
                        }
                    });
                    console.log("成功加载交易日历数据，数量:", Object.keys(self.tradingCalendarData).length);
                    
                    // 重新生成日历，更新交易日标记
                    var calendarHtml = self.generateDateCalendarWithYearMonth(year, month);
                    $('#' + self.options.calendarId).html(calendarHtml);
                    self.bindYearMonthSelectorEvents();
                } else {
                    console.log("未加载到交易日历数据，年份:", year, "响应:", data);
                }
            },
            error: function(xhr, status, error) {
                console.error("加载交易日历数据失败:", error);
            }
        });
    };

    /**
     * 初始化日期选择框
     */
    SecurityDatePicker.prototype.initDateSelect = function() {
        // 获取当前时间
        var now = new Date();
        var currentHour = now.getHours();
        var currentMinute = now.getMinutes();
        var isAfter1500 = (currentHour > 15) || (currentHour === 15 && currentMinute >= 0);
        
        var todayStr = now.toISOString().split('T')[0];
        var defaultDate;
        
        if (isAfter1500) {
            // 当前时间大于15:00，默认选择当日
            defaultDate = this.findNearestTradingDay(todayStr);
        } else {
            // 当前时间小于等于15:00，默认选择前一个交易日
            defaultDate = this.findPreviousTradingDay(todayStr);
        }
        
        this.setDate(defaultDate);
        console.log("日期选择框初始化完成，当前时间:", currentHour + ":" + currentMinute, "默认日期:", defaultDate);
    };

    /**
     * 获取当前选择的日期
     */
    SecurityDatePicker.prototype.getSelectedDate = function() {
        return this.currentDate;
    };

    /**
     * 设置日期
     */
    SecurityDatePicker.prototype.setDate = function(dateStr) {
        this.currentDate = dateStr;
        $('#' + this.options.inputId).val(dateStr);
    };

    // 导出到全局
    window.SecurityDatePicker = SecurityDatePicker;

})(window, jQuery);

